import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:encrypt/encrypt.dart';
import 'package:kxy_flutter_app/model/http_result.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io';

class LoginModel with ChangeNotifier {
  var userNameCtrl = new TextEditingController();
  var userNameFocusNode = new FocusNode();

  var passwordCtrl = new TextEditingController();
  var passwordFocusNode = new FocusNode();

  LoginModel() {
    var task = SharedPreferences.getInstance();
    task.then((prefs) {
      userNameCtrl.text = prefs.getString('userName');
      passwordCtrl.text = prefs.getString('password');
    });
  }

  Future<HttpResult> login() async {
    if (!this._valid()) return null;

    final key = await this.getPublicKey();
    final parser = RSAKeyParser();
    final publicKey = parser.parse(key);
    final encrypter = Encrypter(RSA(publicKey: publicKey));
    final userName = encrypter.encrypt(userNameCtrl.text).base64;
    final password = encrypter.encrypt(passwordCtrl.text).base64;

    var res = await Http.instance.post(
      '/auth/app/login',
      params: {
        'username': userName,
        'password': password,
        'clientType': Platform.isIOS ? 2 : 1,
      },
      withEntry: false,
    );

    if (res.code == 200) {
      var task = SharedPreferences.getInstance();
      task.then((prefs) {
        prefs.setString('userName', userNameCtrl.text);
        prefs.setString('password', passwordCtrl.text);
      });
    }
    return res;
  }

  Future<String> getPublicKey() async {
    var res = await Http.instance.post('/auth/publickey');
    var key = res.data['publicKey'] as String;
    key = '-----BEGIN PUBLIC KEY-----\n$key\n-----END PUBLIC KEY-----';
    return key;
  }

  bool _valid() {
    if (userNameCtrl.text.isEmpty) {
      userNameFocusNode.requestFocus();
      return false;
    }

    if (passwordCtrl.text.isEmpty) {
      passwordFocusNode.requestFocus();
      return false;
    }

    return true;
  }
}
